<template>
  <div class="create-or-edit">
    <el-form ref="form" :model="resource" label-width="80px">
        <el-form-item label="资源分类">
          <el-select v-model="resource.categoryId" placeholder="资源分类">
            <el-option v-for="item in categorie"
               :label="item.name" :key="item.id" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称">
            <el-input v-model="resource.name"></el-input>
        </el-form-item>
        <el-form-item label="路径">
            <el-input v-model="resource.url"></el-input>
        </el-form-item>
        <el-form-item label="描述">
            <el-input v-model="resource.description"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleDisable(0)">取 消</el-button>
          <el-button type="primary" @click="handleDisable(1)">确 定</el-button>
        </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getResourceCategories, saveOrUpdate, getResourceById } from '@/services/resource'

export default {
  props: {
    isEdit: {
      type: Boolean,
      default: false,
      require: true
    },
    resourceId: {
      type: [Number, String],
      require: false
    }
  },
  data () {
    return {
      categorie: [],
      resource: {
        name: '',
        categoryId: null,
        url: '',
        description: ''
      }
    }
  },
  methods: {
    async handleDisable (type) {
      // 执行添加或编辑操作
      const { data } = await saveOrUpdate(this.resource)
      console.log(data)
      if (data.code === '000000') {
        this.$message.success(this.isEdit ? '修改成功' : '添加成功')
      }
      this.resource = {
        name: '',
        categoryId: null,
        url: '',
        description: ''
      }
      // this.resourceId = 0
      this.$emit('handleDisable', type)
    },
    async loadCategoryData () {
      const { data } = await getResourceCategories()
      console.log('============', data.data)
      if (data.code === '000000') {
        this.categorie = data.data
      }
    },
    async loadResource () {
      if (this.isEdit) {
        // this.resourceId
        const { data } = await getResourceById(this.resourceId)
        if (data.code === '000000') {
          this.resource = data.data
        }
      }
    }
  },
  watch: {
    isEdit () {
      this.loadResource()
    },
    resourceId (value, value1) {
      console.log(value, value1)
      this.loadResource()
    }
  },
  created () {
    this.loadCategoryData()
    // 如果是编辑，则获取即将要编辑的数据
    this.loadResource()
  }
}
</script>

<style>

</style>
